package com.markerhub.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.code.kaptcha.Producer;
import com.markerhub.common.lang.Const;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.SysUser;
import com.markerhub.entity.SysUserRole;
import com.markerhub.service.SysUserService;
import com.markerhub.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class AuthController extends BaseController{

	@Autowired
	Producer producer;
	@Autowired
	BCryptPasswordEncoder passwordEncoder;


	@GetMapping("/captcha")
	public Result captcha() throws IOException {

		//采用雪花算法，纯数字
		String key = IdWorker.getIdStr();
		String code = producer.createText();

		BufferedImage image = producer.createImage(code);
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ImageIO.write(image, "jpg", outputStream);

		BASE64Encoder encoder = new BASE64Encoder();
		String str = "data:image/jpeg;base64,";

		String base64Img = str + encoder.encode(outputStream.toByteArray());

		redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);

		return Result.succ(
				MapUtil.builder()
						.put("token", key)
						.put("captchaImg", base64Img)
						.build()

		);
	}

	/**
	 * 获取用户信息接口
	 * @param principal
	 * @return
	 */
	@GetMapping("/sys/userInfo")
	public Result userInfo(Principal principal) {

		SysUser sysUser = sysUserService.getByUsername(principal.getName());

		return Result.succ(MapUtil.builder()
				.put("id", sysUser.getId())
				.put("username", sysUser.getUsername())
				.put("avatar", sysUser.getAvatar())
				.put("created", sysUser.getCreated())
				.put("phone",sysUser.getPhone())
				.put("email",sysUser.getEmail())
				.put("city",sysUser.getCity())
				.map()
		);
	}


	//获取邮箱验证码
	@GetMapping("/gainCode")
	public Result gainCode(String email){
		String code  = "";
		try{
			for(int i = 0 ; i<6 ; i++){
				code  += new Random().nextInt(10);
			}
			MailUtils.sendMail(email,"你的邮箱证件码为" + code + ",验证码的有效时间只有两分钟!","营养膳食系统");
			//前后端分离，采用redis进行保存
			redisUtil.set(email,code,120);
		}catch (Exception e){
			return Result.fail("获取验证码失败");
		}
		return  Result.succ("验证码获取成功");
	}

	//注册
	@Transactional
	@PostMapping("/register")
	public Result register(@RequestBody SysUser user){
		//判断验证码
		String tCode = (String) redisUtil.get(user.getEmail());
		if(tCode== null || !tCode.equals(user.getCode())) {
			return Result.fail("验证码不正确");
		}
		//用户名存在时也是不能增加
		List<SysUser> list = sysUserService.list();
		for (SysUser sysUser : list) {
			if(sysUser.getUsername().equals(user.getUsername())){
				return Result.fail("用户名已经存在,请更换一个");
			}
		}
		user.setAvatar(Const.DEFULT_AVATAR);
		user.setStatu(1);
		user.setPassword(passwordEncoder.encode(user.getPassword()));
		user.setCreated(LocalDateTime.now());
		sysUserService.save(user);
		//分配权限，权限为普通用户
		SysUserRole sysUserRole = new SysUserRole();
		sysUserRole.setUserId(user.getId());
		sysUserRole.setRoleId(3L);
		sysUserRoleService.save(sysUserRole);
		return Result.succ("注册成功");
	}


}
